package com.tvunetworks.center.user.service.impl;

import com.tvunetworks.center.common.constant.LocalConstant;
import com.tvunetworks.center.common.exception.ServerException;
import com.tvunetworks.center.common.model.LoginUser;
import com.tvunetworks.center.common.util.MyUtil;
import com.tvunetworks.center.common.util.Result;
import com.tvunetworks.center.common.util.ResultUtil;
import com.tvunetworks.center.user.mapper.FeatureMapper;
import com.tvunetworks.center.user.mapper.MenuBarMapper;
import com.tvunetworks.center.user.mapper.UserFeatureMapper;
import com.tvunetworks.center.user.model.Feature;
import com.tvunetworks.center.user.model.RoleUser;
import com.tvunetworks.center.user.model.User;
import com.tvunetworks.center.user.model.UserFeature;
import com.tvunetworks.center.user.model.param.AddOrRemoveUserFeatureParam;
import com.tvunetworks.center.user.model.param.AddRoleUserParam;
import com.tvunetworks.center.user.model.result.ResultConstant;
import com.tvunetworks.center.user.model.vo.FeatureVo;
import com.tvunetworks.center.user.model.vo.RoleUserVo;
import com.tvunetworks.center.user.model.vo.UpdateUserFeatureVo;
import com.tvunetworks.center.user.model.vo.UserFeatureVo;
import com.tvunetworks.center.user.service.*;
import com.tvunetworks.center.user.util.UserThreadPool;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.concurrent.CountDownLatch;

/**
 * @program: tvucc-aggregator
 * @description: UserFeatureServiceImpl
 * @author lebronchen
 * @create: 2019-06-10 15:58
 **/
@Service
@Slf4j
public class UserFeatureServiceImpl extends BaseService<UserFeature> implements UserFeatureService {

    @Autowired
    private UserFeatureMapper userFeatureMapper;
    @Autowired
    private FeatureService featureService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserFeatureRecordService userFeatureRecordService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private FeatureMapper featureMapper;
    @Autowired
    private MenuBarMapper menuBarMapper;
    @Autowired
    private RoleUserService roleUserService;

    @Value("${enable.feature.control}")
    private boolean enableFeatureControl;

    @Override
    @Deprecated
    public void initUserFeature() {
        // 查出所有的Admin
        List<String> adminIds = userService.listUserIdByRole(LocalConstant.UserRole.ADMIN);
        if (CollectionUtils.isEmpty(adminIds)) {
            log.error("InitUserFeature adminIds is empty");
            return;
        }

        // 初始化 feature和id的关系
        List<FeatureVo> features = featureService.listAll();
        if (CollectionUtils.isEmpty(features)) {
            log.error("InitUserFeature UserFeature is empty");
            return;
        }
        Map<String, String> featureMap = new HashMap<>();
        for (FeatureVo feature : features) {
            featureMap.put(feature.getFeature(), feature.getId());
        }
        // 查出 AdminAutoOwn的feature
        List<String> adminAutoOwnFeatureIds = featureMapper.listAdminAutoOwnFeatureIds();
        // 查出非 AutoOwn 的 menus
        List<String> menus = menuBarMapper.listNotAutoOwnMenus();



        for (String adminId : adminIds) {
            // 用户拥有的UserRole
            List<String> adminRoles = userFeatureMapper.listUserEnableRole(adminId);

            // 保存 Admin 拥有的Feature，用于在为 User 设置feature的时候做过滤
            Set<String> adminEnableFeatures = new HashSet<>(adminAutoOwnFeatureIds);
            for (String roleFeature : adminRoles) {
                if (adminAutoOwnFeatureIds.contains(roleFeature)) {
                    // Admin 默认拥有该Feature
                    continue;
                }
                String featureId = featureMap.get(roleFeature);
                if (StringUtils.isEmpty(featureId)) {
                    // UserRole 中的 feature，在新 Feature 表中不存在
                    continue;
                }
                // 创建 UserFeature
                addUserFeature(adminId, featureId);
                adminEnableFeatures.add(roleFeature);
            }

            // 保存 Admin 不拥有的Feature，用于在为 User 设置feature的时候做过滤
            Set<String> adminDisableFeatures = new HashSet<>(adminAutoOwnFeatureIds);
            List<String> adminDisableRoles = userFeatureMapper.listUserEnableRole(adminId);
            for (String menu : menus) {
                if (adminDisableRoles.contains(menu)) {
                    // 用户没有这个页面的权限
                    continue;
                }
                String featureId = featureMap.get(menu);
                if (StringUtils.isEmpty(featureId)) {
                    // UserRole 中的 feature，在新 Feature 表中不存在
                    continue;
                }
                // 创建 UserFeature
                addUserFeature(adminId, featureId);
                adminDisableFeatures.add(menu);
            }

            // 为 User 设置 UserFeature
            List<String> userIds = userService.listSonUserIds(adminId);
            if (CollectionUtils.isEmpty(userIds)) {
                continue;
            }
            for (String userId : userIds) {
                // 用户拥有的UserRole
                List<String> userRoles = userFeatureMapper.listUserEnableRole(adminId);
                if (CollectionUtils.isEmpty(userRoles)) {
                    continue;
                }
                for (String roleFeature : userRoles) {
                    if (!adminEnableFeatures.contains(roleFeature)) {
                        continue;
                    }
                    String featureId = featureMap.get(roleFeature);
                    if (StringUtils.isEmpty(featureId)) {
                        // UserRole 中的 feature，在新 Feature 表中不存在
                        continue;
                    }
                    // 创建 UserFeature
                    addUserFeature(userId, featureId);
                }

                List<String> userDisableRoles = userFeatureMapper.listUserEnableRole(userId);
                for (String menu : menus) {
                    if (userDisableRoles.contains(menu)) {
                        // 用户没有这个页面的权限
                        continue;
                    }
                    if (adminDisableFeatures.contains(menu)) {
                        continue;
                    }
                    String featureId = featureMap.get(menu);
                    if (StringUtils.isEmpty(featureId)) {
                        // UserRole 中的 feature，在新 Feature 表中不存在
                        continue;
                    }
                    // 创建 UserFeature
                    addUserFeature(userId, featureId);
                }
            }
        }
    }

    @Deprecated
    private void addUserFeature(String userId, String featureId){
        UserFeature record = new UserFeature().setUserId(userId).setFeatureId(featureId);
        UserFeature exist = super.selectExistOne(record);
        if (exist == null){
            record.setEnable(1);
            super.insert(record);
        }
    }

//    @Override
//    public Map<String, List<UserFeatureVo>> listUserFeature(String userId) {
//        Map<String, List<UserFeatureVo>> map = new HashMap<>();
//        map.put(UserConstant.Feature.ADMIN_AUTO_OWN_KEY, new ArrayList<>());
//        map.put(UserConstant.Feature.NOT_ADMIN_AUTO_OWN_KEY, new ArrayList<>());
//        User user = userService.getById(userId);
//        if (user == null) {
//            return map;
//        }
//
//        String role = user.getRole();
//        List<UserFeatureVo> adminAutoOwnFeatures = new ArrayList<>();
//        if (StringUtils.equals(role, LocalConstant.UserRole.ADMIN)) {
//            // admin feature
//            // 查出admin 默认拥有的feature
//            List<FeatureVo> autoOwnFeatures = featureService.listAdminAutoOwnFeature();
//            if (autoOwnFeatures != null && autoOwnFeatures.size() > 0) {
//                for (FeatureVo feature : autoOwnFeatures) {
//                    UserFeatureVo vo = new UserFeatureVo()
//                            .setEnName(feature.getEnName())
//                            .setCnName(feature.getCnName())
//                            .setFeatureId(feature.getId());
//                    adminAutoOwnFeatures.add(vo);
//                }
//            }
//            map.put(UserConstant.Feature.ADMIN_AUTO_OWN_KEY, adminAutoOwnFeatures);
//        } else {
//            // user feature
//            // 查出用户对于admin默认拥有的feature的拥有情况
//            adminAutoOwnFeatures = userFeatureMapper.listAdminAutoOwnUserFeature(userId);
//            if (adminAutoOwnFeatures == null || adminAutoOwnFeatures.size() == 0) {
//                adminAutoOwnFeatures = new ArrayList<>();
//            }
//            map.put(UserConstant.Feature.ADMIN_AUTO_OWN_KEY, adminAutoOwnFeatures);
//        }
//
//        // 用户对于非admin默认拥有的feature的拥有情况
//        List<UserFeatureVo> otherFeatures = userFeatureMapper.listUserFeatureWithoutAdminAutoOwn(userId);
//        if (otherFeatures == null || otherFeatures.size() == 0) {
//            otherFeatures = new ArrayList<>();
//        }
//        map.put(UserConstant.Feature.NOT_ADMIN_AUTO_OWN_KEY, otherFeatures);
//        return map;
//    }

    @Override
    @Transactional
    public int addOrRemoveFeature(AddOrRemoveUserFeatureParam param) {
        String userId = param.getUserId();
        String enableFeatureIds = param.getEnableFeatureIds();
        if (StringUtils.isNotBlank(enableFeatureIds)) {
            String[] featureIds = enableFeatureIds.split(",");
            for (String featureId : featureIds) {
                this.addOrRemoveFeature(userId, featureId, 1, false);
            }
        }
        String disAbleFeatureIds = param.getDisAbleFeatureIds();
        if (StringUtils.isNotBlank(disAbleFeatureIds)) {
            String[] featureIds = disAbleFeatureIds.split(",");
            for (String featureId : featureIds) {
                this.addOrRemoveFeature(userId, featureId, 0, false);
            }
        }
        return 0;
    }

    @Override
    public Result<Object> addOrRemoveFeature(LoginUser loginUser, AddOrRemoveUserFeatureParam param) {
        String userId = param.getUserId();
        User user = userService.getById(userId);
        if (user == null) {
            return ResultConstant.User.USER_NOT_EXIST;
        }
        if (LocalConstant.UserRole.ADMIN.equals(loginUser.getRole())) {
            String roleId = param.getRoleId();
            if (!StringUtils.equals(user.getRole(), LocalConstant.UserRole.USER)
                    || StringUtils.isEmpty(user.getUserParentId()) || !StringUtils.equals(user.getUserParentId(), loginUser.getId())) {
                return ResultUtil.error("81000609", "user can not exist or id not user permission or dose not belong of account");
            }
            RoleUser roleUser = roleUserService.getByUserId(userId);
            if (StringUtils.isNotEmpty(roleId)) {
                AddRoleUserParam userParam = new AddRoleUserParam()
                        .setUserId(userId)
                        .setRoleId(roleId);
                return roleUserService.add(loginUser, userParam);
            } else {
                if (roleUser != null) {
                    roleUserService.deleteByRoleUser(roleUser);
                }
                List<String> addFeatureIds = new ArrayList<>(Arrays.asList(param.getEnableFeatureIds().split(",")));
                List<String> deleteFeatureIds = new ArrayList<>(Arrays.asList(param.getDisAbleFeatureIds().split(",")));
                this.addAndRemoveFeatureListByUserId(userId, user.getRole(), user.getUserParentId(), addFeatureIds, deleteFeatureIds);
            }
        }else {
            if (StringUtils.isEmpty(param.getDisAbleFeatureIds()) && StringUtils.isEmpty(param.getEnableFeatureIds())) {
                return ResultUtil.success();
            }
            List<String> addFeatureIds = new ArrayList<>(Arrays.asList(param.getEnableFeatureIds().split(",")));
            List<String> deleteFeatureIds = new ArrayList<>(Arrays.asList(param.getDisAbleFeatureIds().split(",")));
            this.addAndRemoveFeatureListByUserId(userId, user.getRole(), user.getUserParentId(), addFeatureIds, deleteFeatureIds);
        }
        return ResultUtil.success();
    }

    @Override
    public void addAndRemoveFeatureListByUserId(String userId, String userRole, String userParentId, List<String> addFeatureIds, List<String> removeFeatureIds) {
        if (!CollectionUtils.isEmpty(removeFeatureIds)) {
            final CountDownLatch countDownLatch = new CountDownLatch(removeFeatureIds.size());
            removeFeatureIds.forEach(s->{
                UserThreadPool.SERVICETHREADPOOL.execute(()->{
                    try {
                        Feature feature = featureService.getById(s);
                        if (feature == null) {
                            log.error("RemoveFeatureList>>>>>>>this feature not exist>>>>>featureId:[{}],userId:[{}]", s, userId);
                            return;
                        }
                        UserFeature userFeature = userFeatureMapper.getUserFeatureByFeatureIdAndUserId(userId, s);
                        if (userFeature != null && userFeature.getEnable() == 1) {
                            userFeature.setEnable(0);
                            super.updateSelective(userFeature);
                            userFeatureRecordService.addUserFeatureRecord(userFeature);
                        }else {
                            log.error("RemoveFeatureList>>>>>>>user have not this feature>>>>>featureId:[{}],userId:[{}]", s, userId);
                        }
                        userRoleService.updateUserRole(userId, feature.getFeature(), 0);
                    }finally {
                        countDownLatch.countDown();
                    }
                });
            });
            try {
                countDownLatch.await();
            } catch (InterruptedException e) {
                log.error("countDownLatch await is exception:[{}]", e);
            } finally {
                countDownLatch.countDown();
            }
        }
        if (!CollectionUtils.isEmpty(addFeatureIds)) {
            final CountDownLatch countDownLatch = new CountDownLatch(addFeatureIds.size());
            addFeatureIds.forEach(s->{
                UserThreadPool.SERVICETHREADPOOL.execute(()->{
                    try {
                        Feature feature = featureService.getById(s);
                        if (feature == null) {
                            //feature不存在，则不用添加
                            log.error("AddFeatureList>>>>>>>this feature not exist>>>>>featureId:[{}],userId:[{}]", s, userId);
                            return;
                        }
                        //表示不是admin默认拥有的权限,则需以下校验
                        if (1!=feature.getAdminAutoOwn()) {
                            if (StringUtils.equalsIgnoreCase(LocalConstant.UserRole.USER, userRole)) {
                                UserFeature parentUserFeature = userFeatureMapper.getUserFeatureByFeatureIdAndUserId(userParentId, s);
                                if (parentUserFeature == null){
                                    //该用户的父账号没有该feature，则不用添加
                                    log.error("AddFeatureList>>>>>>>this parentUser not this feature>>>>>featureId:[{}],parentUserId:[{}],userId:[{}]",
                                            s, userParentId, userId);
                                    return;
                                }
                            }
                        }
                        UserFeature userFeature = userFeatureMapper.getUserFeatureByFeatureIdAndUserId(userId, s);
                        if (userFeature == null) {
                            userFeature = new UserFeature()
                                    .setFeatureId(s)
                                    .setUserId(userId)
                                    .setEnable(1);
                            super.insert(userFeature);
                            userFeatureRecordService.addUserFeatureRecord(userFeature);
                        } else if (userFeature.getEnable() == 0) {
                            userFeature.setEnable(1);
                            super.updateSelective(userFeature);
                            userFeatureRecordService.addUserFeatureRecord(userFeature);
                        }else {
                            log.error("AddFeatureList>>>>>>>user already have this feature>>>>>featureId:[{}],userId:[{}]", s, userId);
                        }
                        userRoleService.updateUserRole(userId, feature.getFeature(), 1);
                    }finally {
                        countDownLatch.countDown();
                    }
                });
            });
            try {
                countDownLatch.await();
            } catch (InterruptedException e) {
                log.error("countDownLatch await is exception:[{}]", e);
            } finally {
                countDownLatch.countDown();
            }
        }
    }

    private int addOrRemoveFeature(String userId, String featureId, int enable, boolean forApi) {
        // 检测目标用户是否存在
        User user = userService.getById(userId);
        if (user == null) {
            // 目标用户不存在
            return 1;
        }
        String role = user.getRole();
        if (StringUtils.equals(role, LocalConstant.UserRole.USER)) {
            String userParentId = user.getUserParentId();
            if (StringUtils.isBlank(userParentId)) {
                // 没有父亲的user，不能修改feature
                return 2;
            }
            User parent = userService.getById(userParentId);
            if (parent == null) {
                // user 的父亲不存在
                return 3;
            }
            boolean existFeature = this.isUserExistFeature(userParentId, featureId);
            if (!existFeature) {
                // user 的父亲没有这个feature
                return 4;
            }
        }

        Feature feature = featureService.getById(featureId);
        if (feature == null) {
            // feature 不存在
            return 6;
        }
        if (StringUtils.equals(LocalConstant.UserRole.ADMIN, user.getRole()) && feature.getAdminAutoOwn() == 1) {
            // admin 自动有用该feature，不用设置
            return 7;
        }


        UserFeature userFeature = new UserFeature()
                .setUserId(userId)
                .setFeatureId(featureId);
        userFeature = super.selectExistOne(userFeature);
        if (userFeature == null) {
            // UserFeature不存在
//            if (enable == 0) {
//                // 用户feature已经是当前状态
//                return 5;
//            }
            userFeature = new UserFeature()
                    .setUserId(userId)
                    .setFeatureId(featureId)
                    .setEnable(enable);
            super.insert(userFeature);
            // 增加UserFeatureRecord
            userFeatureRecordService.addUserFeatureRecord(userFeature);
        } else {
            // UserFeature已存在
            if (enable == userFeature.getEnable()) {
                // 用户feature已经是当前状态
                return 5;
            }
            userFeature.setEnable(enable);

            super.updateSelective(userFeature);
            // 增加UserFeatureRecord
            userFeatureRecordService.addUserFeatureRecord(userFeature);
        }

        // 如果移除admin的feature，需要同时移除admin孩子的feature
        if (enable == 0 && StringUtils.equals(LocalConstant.UserRole.ADMIN, role)) {
            // 查询admin用户创建的user用户中 某个feature时enable的UserFeature
            List<UserFeature> sonFeatures = userFeatureMapper.listAdminSonEnableFeature(userId, featureId);
            if (sonFeatures != null && sonFeatures.size() > 0) {
                for (UserFeature sonFeature : sonFeatures) {
                    sonFeature.setEnable(0);
                    super.updateSelective(sonFeature);
                    // 增加UserFeatureRecord
                    userFeatureRecordService.addUserFeatureRecord(userFeature);
                }
            }
            // 如果是tvucc修改了UserRole，调用本服务修改UserFeature，那么不用再修改UserRole
            userRoleService.removeUserSonRole(userId, feature.getFeature());
        }
        // 如果是tvucc修改了UserRole，调用本服务修改UserFeature，那么不用再修改UserRole
        if (!forApi) {
            userRoleService.updateUserRole(userId, feature.getFeature(), enable);
        }
        return 0;
    }

    @Override
    public boolean isUserExistFeature(String userId, String featureId) {
        User user = userService.getById(userId);
        if (user == null) {
            return false;
        }
        Feature feature = featureService.getById(featureId);
        if (feature == null) {
            return false;
        }
        if (StringUtils.equals(LocalConstant.UserRole.ADMIN, user.getRole()) && feature.getAdminAutoOwn() == 1) {
            // admin 默认拥有 admin默认拥有的feature
            return true;
        }
        UserFeature userFeature = new UserFeature()
                .setUserId(userId)
                .setFeatureId(featureId)
                .setEnable(1);
        List<UserFeature> existList = super.selectExistList(userFeature);
        return existList != null && existList.size() > 0;
    }

    @Override
    public boolean isUserExistFeatureName(String userId, String feature) {
        Feature fea = featureService.getByFeature(feature);
        if (fea == null) {
            return false;
        }
        return isUserExistFeature(userId, fea.getId());
    }

    @Override
    public void apiUpdateUserRole(String userId, String feature, Integer enable) {
        Feature featureItem = featureService.getByFeature(feature);
        if (featureItem == null) {
            log.error("apiUpdateUserRole failed feature not exist  userId:[{}], feature[{}], enable[{}]", userId, feature, enable);
            return;
        }
        // 修改UserFeature
        addOrRemoveFeature(userId, featureItem.getId(), enable, true);
    }

    @Override
    public void removeUserFeatureByFeatureId(String featureId) {
        UserFeature record = new UserFeature().setFeatureId(featureId);
        super.deleteLogicByWhere(record);
    }

    @Override
    public Result<UpdateUserFeatureVo> listFeatureForCreate(LoginUser loginUser, String targetUserRole) {
        String loginUserRole = loginUser.getRole();
        String loginUserId = loginUser.getId();
        UpdateUserFeatureVo result = new UpdateUserFeatureVo();
         if (StringUtils.equals(LocalConstant.UserRole.SUPPORT, loginUserRole)) {
             if (StringUtils.equals(LocalConstant.UserRole.ADMIN, targetUserRole)) {
                // Support 创建 Admin
                // 1.不需要查询 AdminAutoOwn 的 feature
                 result.setAdminAutoOwnFeature(false);
                // 2.查询 AccessPages
                result.setAccessPage(true);
                List<String> featureIds = userFeatureMapper.listUserMenuFeatureIds(null);
                if (!CollectionUtils.isEmpty(featureIds)) {
                    List<UserFeatureVo> featureVos = featureMapper.listFeatureVoByFeatureIds(featureIds);
                    result.setAccessPages(featureVos);
                }
                // 3.查询非 AdminAutoOwn 的 feature
                      result.setOtherFeature(enableFeatureControl);
                if (enableFeatureControl) {
                    featureIds = userFeatureMapper.listUserNotMenuNotAdminAutoOwnFeatureIds(null);
                    if (!CollectionUtils.isEmpty(featureIds)) {
                        List<UserFeatureVo> featureVos = featureMapper.listFeatureVoByFeatureIds(featureIds);
                        result.setOtherFeatures(featureVos);
                    }
                }
            } else if (StringUtils.equals(LocalConstant.UserRole.USER, targetUserRole)) {
                // Support 创建 User
                // 1.查询 AdminAutoOwn 的 feature
                result.setAdminAutoOwnFeature(true);
                List<String> featureIds = featureMapper.listAdminAutoOwnFeatureIds();
                if (!CollectionUtils.isEmpty(featureIds)) {
                    List<UserFeatureVo> featureVos = featureMapper.listFeatureVoByFeatureIds(featureIds);
                    result.setAdminAutoOwnFeatures(featureVos);
                }
                // 2.不需要查询 AccessPages
                result.setAccessPage(false);
                // 3.不需要查询非 AdminAutoOwn 的 feature
                result.setOtherFeature(false);
            } else {
                // 错误
                return ResultUtil.error("81001401","LoginUser is Support, but target UserRole is not Admin or User", targetUserRole);
            }
        } else if (StringUtils.equals(LocalConstant.UserRole.ADMIN, loginUserRole)) {
            if (StringUtils.equals(LocalConstant.UserRole.USER, targetUserRole)) {
                // Admin 创建 User
                // 1.查询 AdminAutoOwn 的 feature
                result.setAdminAutoOwnFeature(true);
                List<String> featureIds = featureMapper.listAdminAutoOwnFeatureIds();
                if (!CollectionUtils.isEmpty(featureIds)) {
                    List<UserFeatureVo> featureVos = featureMapper.listFeatureVoByFeatureIds(featureIds);
                    result.setAdminAutoOwnFeatures(featureVos);
                }
                // 2.查询 AccessPages
                result.setAccessPage(true);
                featureIds = userFeatureMapper.listUserMenuFeatureIds(loginUserId);
                if (!CollectionUtils.isEmpty(featureIds)) {
                    List<UserFeatureVo> featureVos = featureMapper.listFeatureVoByFeatureIds(featureIds);
                    result.setAccessPages(featureVos);
                }
                // 3.查询非 AdminAutoOwn 的 feature
                result.setOtherFeature(enableFeatureControl);
                if (enableFeatureControl) {
                    featureIds = userFeatureMapper.listUserNotMenuNotAdminAutoOwnFeatureIds(loginUserId);
                    if (!CollectionUtils.isEmpty(featureIds)) {
                        List<UserFeatureVo> featureVos = featureMapper.listFeatureVoByFeatureIds(featureIds);
                        result.setOtherFeatures(featureVos);
                    }
                }
            } else {
                // 错误
                return ResultUtil.error("81001402","LoginUser is Admin, but target UserRole not user", targetUserRole);
            }
        } else if (StringUtils.equals(LocalConstant.UserRole.SUPER_ADMIN, loginUserRole)){
            if (StringUtils.equals(LocalConstant.UserRole.SUPPORT, targetUserRole)){
                // SuperAdmin 创建 Support
                result.setAdminAutoOwnFeature(false);
                result.setAccessPage(false);
                result.setOtherFeature(false);
                return ResultUtil.success(result);
            } else {
                return ResultUtil.error("81001403","LoginUser is SuperAdmin, but target UserRole not support", targetUserRole);
            }
        } else {
            // 错误
            return ResultUtil.error("81001404","Login UserRole not SuperAdmin, Support and Admin", loginUserRole);
        }
        return ResultUtil.success(result);
    }

    @Override
    public Result<UpdateUserFeatureVo> listFeatureForModify(LoginUser loginUser, String modifyUserId) {
        User modifyUser = userService.getById(modifyUserId);
        if (modifyUser == null) {
            // 错误 用户不存在
            return ResultUtil.error("81001405", "Target user not exist");
        }
        String loginUserRole = loginUser.getRole();
        String modifyUserRole = modifyUser.getRole();
        if (!(StringUtils.equals(LocalConstant.UserRole.SUPPORT, loginUserRole) && StringUtils.equals(LocalConstant.UserRole.ADMIN, modifyUserRole))
            && !(StringUtils.equals(LocalConstant.UserRole.ADMIN, loginUserRole) && StringUtils.equals(LocalConstant.UserRole.USER, modifyUserRole))) {
            log.error("ListFeatureForModify UserRole no authority loginUserRole:[{}] modifyUserRole:[{}]", loginUserRole, modifyUserRole);
            return ResultUtil.noAuthority();
        }

        if (StringUtils.equals(LocalConstant.UserRole.ADMIN, loginUserRole) && StringUtils.equals(LocalConstant.UserRole.USER, modifyUserRole)) {
            if (!StringUtils.equals(loginUser.getId(), modifyUser.getUserParentId())) {
                log.error("ListFeatureForModify not parent no authority loginUserId:[{}] modifyUserParentId:[{}]", loginUser.getId(), modifyUser.getUserParentId());
                return ResultUtil.noAuthority();
            }
        }

        // 查询出所有可勾选的框
        Result<UpdateUserFeatureVo> result = this.listFeatureForCreate(loginUser, modifyUserRole);
        if (!result.assertSuccess()) {
            return result;
        }

        // 通过 UserFeature 来对所有可勾选的框进行赋值（enable属性）
        UpdateUserFeatureVo vo = result.getResult();
        List<UserFeatureVo> adminAutoOwnFeatures = vo.getAdminAutoOwnFeatures();
        if (!CollectionUtils.isEmpty(adminAutoOwnFeatures)) {
            setUserFeatureVoEnableField(modifyUserId, adminAutoOwnFeatures);
        }
        List<UserFeatureVo> accessPageFeatures = vo.getAccessPages();
        if (!CollectionUtils.isEmpty(accessPageFeatures)) {
            setUserFeatureVoEnableField(modifyUserId, accessPageFeatures);
        }
        List<UserFeatureVo> otherOwnFeatures = vo.getOtherFeatures();
        if (!CollectionUtils.isEmpty(otherOwnFeatures)) {
            setUserFeatureVoEnableField(modifyUserId, otherOwnFeatures);
        }
        RoleUserVo roleUser = roleUserService.getUserRoleVoByUserId(modifyUserId);
        if (roleUser != null) {
            vo.setRoleId(roleUser.getRoleId());
            vo.setRoleName(roleUser.getRoleName());
        }

/*        if (StringUtils.equals(LocalConstant.UserRole.SUPPORT, loginUserRole)) {
            if (StringUtils.equals(LocalConstant.UserRole.ADMIN, modifyUserRole)) {
                // Support 为 Admin 修改权限
            } else {
                // 错误
                return null;
            }
        } else if (StringUtils.equals(LocalConstant.UserRole.ADMIN, loginUserRole)) {
            if (StringUtils.equals(LocalConstant.UserRole.USER, modifyUserRole)) {
                // Admin 为 User 修改权限
            } else {
                // 错误
                return null;
            }
        } else {
            // 错误
            return null;
        }*/
        return ResultUtil.success(vo);
    }

    @Override
    public List<String> listAllUserEnableFeatureIds(String userId) {
        User user = userService.getById(userId);
        if (user == null) {
            return new ArrayList<>();
        }
        Set<String> resultSet = new HashSet<>();
        // UserFeature enable 的featureIds
        List<String> userFeatureIds = userFeatureMapper.listUserEnableFeatureIds(userId);
        if (!CollectionUtils.isEmpty(userFeatureIds)) {
            resultSet.addAll(userFeatureIds);
        }
        // Admin AutoOwn 的featureIds
        if (StringUtils.equals(LocalConstant.UserRole.ADMIN, user.getRole())) {
            List<String> adminAutoOwnFeatureIds = featureMapper.listAdminAutoOwnFeatureIds();
            if (!CollectionUtils.isEmpty(adminAutoOwnFeatureIds)) {
                resultSet.addAll(adminAutoOwnFeatureIds);
            }
        }
        // Menu autoOwn 对应的feature
        List<String> autoOwnMenuFeatureIds = menuBarMapper.listAutoOwnMenuFeatureIds();
        if (!CollectionUtils.isEmpty(autoOwnMenuFeatureIds)) {
            resultSet.addAll(autoOwnMenuFeatureIds);
        }
        return new ArrayList<>(resultSet);
    }

    @Override
    public Result<Object> initAllHome(String name) {
        Feature feature = featureService.getByFeature(name);
        if (feature == null) {
            return ResultUtil.error("101", "Feature not exist");
        }
        HashMap<String, Object> map = new HashMap<>();

        String featureId = feature.getId();

        Set<String> allUserIds = new HashSet<>();
        List<String> adminIds = userService.listUserIdByRole("3");
        if (!CollectionUtils.isEmpty(adminIds)) {
            allUserIds.addAll(adminIds);
        }
        List<String> userIds = userService.listUserIdByRole("4");
        if (!CollectionUtils.isEmpty(userIds)) {
            allUserIds.addAll(userIds);
        }
        map.put("userCount", allUserIds.size());

        int count = 0;
        for (String userId : allUserIds) {
            UserFeature record = new UserFeature()
                    .setUserId(userId)
                    .setFeatureId(featureId);
            UserFeature exist = super.selectExistOne(record);
            if (exist == null) {
                record.setEnable(1);
                super.insert(record);
                count ++;
            } else {
                Integer enable = exist.getEnable();
                if (enable == 0) {
                    exist.setEnable(1);
                    super.update(exist);
                }
                count ++;
            }

        }
        map.put("activeCount", count);
        return ResultUtil.success(map);
    }

    @Override
    public boolean userHasFeature(String userId, String featureName) {

        // 当有一个参数为 null 则直接返回false
        if (StringUtils.isEmpty(userId) || StringUtils.isEmpty(featureName)) {
            log.error("userHasFeature return false,userId : [{}],featureName:[{}]", userId, featureName);
            return false;
        }

        Feature feature = featureService.getByFeature(featureName);


        if (feature == null) {
            log.info("Feature not exist,user id: {}, feature name: {}",userId,featureName);
            return false;
        }

        UserFeature condition = new UserFeature()
                .setUserId(userId)
                .setFeatureId(feature.getId())
                .setEnable(LocalConstant.ENABLE);


        UserFeature userFeature = selectExistOne(condition);


        // 如果查到了就说明拥有该权限
        return userFeature != null;
    }

    @Override
    public void removeUserAllFeature(String userId) {
        if (StringUtils.isBlank(userId)) {
            return;
        }
        UserFeature userFeature = new UserFeature();
        userFeature.setUserId(userId);
        log.error("removeUserAllFeature userId:[{}]", userId);
        super.deleteLogicByWhere(userFeature);
    }

    /**
     * 根据UserId为UserFeatureVo列表设置enable属性
     * @param userId
     */
    private void setUserFeatureVoEnableField(String userId, List<UserFeatureVo> list){
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        List<String> enableFeatureIds = this.listAllUserEnableFeatureIds(userId);

        for (UserFeatureVo userFeatureVo : list) {
            if (enableFeatureIds.contains(userFeatureVo.getFeatureId())) {
                userFeatureVo.setEnable(1);
            } else {
                userFeatureVo.setEnable(0);
            }
        }
    }


    @Override
    public List<UserFeatureVo> listFeatureByUserId(String userId) {
        User user = userService.getById(userId);
        if (user!=null){
            List<UserFeatureVo> userFeatureVos;
            String role = user.getRole();
            if (StringUtils.equals(role,LocalConstant.UserRole.ADMIN)){
                //查询Admin默认拥有的权限和已有权限
                userFeatureVos = userFeatureMapper.listUserFeatureWithoutAdminAutoOwn(userId);
                List<UserFeatureVo> adminFeatureVo = userFeatureMapper.listAdminAutoOwnUserFeature(userId);
                userFeatureVos.addAll(adminFeatureVo);
            }else {
                userFeatureVos = userFeatureMapper.listUserFeatureWithoutAdminAutoOwn(userId);
            }
            return userFeatureVos;
        }
        throw new ServerException(ResultConstant.GridEvent.USER_NOT_EXIST);
    }

    @Override
    public Result accreditAllUser() {
        List<String> allList = new ArrayList<>();
        List<String> adminList = userService.listUserIdByRole("3");
        List<String> userList = userService.listUserIdByRole("4");
        allList.addAll(adminList);
        allList.addAll(userList);
        //查询出Grid Schedule 的featureId
        String featureId = userFeatureMapper.getFeatureIdByName("Grid Schedule");
        //查询出已经拥有Grid Schedule权限的账号
        List<String> strings = userFeatureMapper.listUserByFeature(featureId);
        //取差集,那么剩余的都是没有授权Grid Schedule的用户
        allList.removeAll(strings);
        List<String> uuIdList = new ArrayList<>();
        for (String userId : allList) {
            UserFeature feature = new UserFeature();
            feature.setFeatureId(featureId)
                    .setUserId(userId)
                    .setEnable(1)
                    .setCreateTime(System.currentTimeMillis());
            feature.setDeleteFlag(0);
            String uuid = MyUtil.getUUID();
            uuIdList.add(uuid);
            feature.setId(uuid);
            userFeatureMapper.insert(feature);
        }
        log.error("accreditAllUser DB id ===== :[{}]",uuIdList);

        return ResultUtil.success();
    }

    @Override
    public Result deleteUserFeatureById(List<String> id) {
        for (String s : id) {
            userFeatureMapper.deleteByPrimaryKey(s);
        }
        return ResultUtil.success();
    }
}
